package com.theme.passport.controller.theme;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.theme.common.base.ConfigConstant;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.FileUploadParam;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.utils.UploadParams;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.dao.CustomMapper;
import com.theme.passport.entity.SysRoleEntity;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.constant.SysRoleNameEnum;
import com.theme.passport.entity.constant.ThemeAttchmentTypeEnum;
import com.theme.passport.entity.constant.ThemeNtsEnum;
import com.theme.passport.entity.theme.ThemeAttachmentEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.entity.theme.WidgeLayoutEntity;
import com.theme.passport.service.SysRoleService;
import com.theme.passport.service.SysUserRoleService;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.ThemeAttachmentService;
import com.theme.passport.service.theme.ThemeService;
import com.theme.passport.service.theme.WidgeLayoutService;
import com.theme.passport.service.theme.WidgeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 壁纸主题表
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2020-11-23 10:57:59
 */
@RestController
@RequestMapping("theme/theme")
public class ThemeController extends AbstractController {
    @Autowired
    private ThemeService themeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WidgeService widgeService;

    @Autowired
    private WidgeLayoutService widgeLayoutService;

    @Autowired
    private ThemeAttachmentService attachmentService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Value("${theme.aliyundir}")
    private String aliyunThemeDir;

    @Value("${theme.aliyunzipdir}")
    private String aliyunThemeZipDir;

    @Autowired
    private CustomMapper customMapper;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("theme:theme:list")
    public R list(@RequestParam Map<String, Object> params){
        // 根据用户查询用户角色，如果是设计师就查询他的，不是则查询所有的
        SysUserEntity user = getUser();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList != null && roleIdList.size() == 1){
            Long userRoleId = roleIdList.get(0) ;
            List<SysRoleEntity> sysRoleList = sysRoleService.queryRoleListByName(SysRoleNameEnum.DESIGNER.getName());
            if (sysRoleList != null && sysRoleList.size() == 1){
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                if (sysRoleEntity.getRoleId().equals(userRoleId)){
                    params.put("userId",user.getUserId() +"");
                }
            }
        }
        PageUtils page = themeService.queryPage(params);
        List<ThemeEntity> list = (List<ThemeEntity>) page.getList();
        list.forEach(theme ->{
            SysUserEntity byId = sysUserService.getById(theme.getUserId());
            theme.setUseNickname(byId.getNickname());
            String label = theme.getLabel();
            if (label != null){
                String[] split = label.split(",");
                theme.setLabels(Arrays.asList(split));
            }
        });
        page.setList(list);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listItem")
    @RequiresPermissions("theme:theme:list")
    public R listItem(@RequestParam Map<String, Object> params) {

        SysUserEntity user = getUser();
        params.put("userId",user.getUserId());

        PageUtils page = themeService.queryPageByStatus(params);
        List<ThemeEntity> list = (List<ThemeEntity>) page.getList();
        list.forEach(theme ->{
            SysUserEntity byId = sysUserService.getById(theme.getUserId());
            theme.setUseNickname(byId.getNickname());
            String label = theme.getLabel();
            if (label != null){
                String[] split = label.split(",");
                theme.setLabels(Arrays.asList(split));
            }
        });
        page.setList(list);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("theme:theme:info")
    public R info(@PathVariable("id") Long id){
        ThemeEntity theme = themeService.getById(id);
        SysUserEntity byId = sysUserService.getById(theme.getUserId());
        theme.setUseNickname(byId.getNickname());
        //获取主题详情图图片：
        QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                .eq("object_id", id));
        List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
        List<String> images = new ArrayList<>();
        attachmentList.forEach(attachment -> {
            images.add(attachment.getFileUrl());
        });
        theme.setImages(images);
        String label = theme.getLabel();
        if (label != null){
            String[] split = label.split(",");
            theme.setLabels(Arrays.asList(split));
        }
        return R.ok().put("theme", theme);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("theme:theme:save")
    public R save(@RequestBody ThemeEntity theme){

        SysUserEntity user = getUser();
        theme.setUserId(user.getUserId());
        theme.setUseNickname(user.getNickname());
        //1.判断主题名称是否已经存在
        String name = theme.getName();
        QueryWrapper<ThemeEntity> nameWrapper = new QueryWrapper<>();
        nameWrapper.and(wrapper -> wrapper
                .eq("name", name));
        List<ThemeEntity> nameList = themeService.list(nameWrapper);
        if (nameList != null && nameList.size() >0 ){
            return R.error("该主题名称已存在,请更改主题名称!");
        }

        //1.判断主题附件名称是否已经存在
        String fileName = theme.getFileName();
        QueryWrapper<ThemeEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("file_name", fileName));
        List<ThemeEntity> fileNameList = themeService.list(fileNameWrapper);
        if (fileNameList != null && fileNameList.size() >0 ){
            return R.error("该主题附件对应的名称已存在,请更改主题附件名称!");
        }

        String label = "";
        List<String> labels = theme.getLabels();
        if (labels != null && labels.size() > 0){
            label = parseListToStr(labels);
            theme.setLabel(label);
        }
        R r = themeService.saveTheme(theme);
        List<ThemeEntity> list = themeService.list(fileNameWrapper);
        List<String> imageList = theme.getImages();
        if (list != null && list.size() >0 && imageList != null && imageList.size() >0){
            ThemeEntity themeEntity = list.get(0);
            List<ThemeAttachmentEntity> listAttachment = new ArrayList<>();
            imageList.forEach(image -> {
                ThemeAttachmentEntity attachment = new ThemeAttachmentEntity();
                attachment.setObjectId(themeEntity.getId());
                attachment.setFileUrl(image);
                attachment.setType(ThemeAttchmentTypeEnum.THEME.getValue());
                attachment.setCreated(new Date());
                listAttachment.add(attachment);
            });
            attachmentService.saveBatch(listAttachment);
        }

        return r;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("theme:theme:update")
    public R update(@RequestBody ThemeEntity theme){
        String label = "";
        List<String> labels = theme.getLabels();
        if (labels != null && labels.size() > 0){
            label = parseListToStr(labels);
        }
        theme.setLabel(label);
        theme.setUpdated(new Date());
        theme.setNts(ThemeNtsEnum.YES.getValue());
		themeService.updateTheme(theme);

        List<String> imageList = theme.getImages();
        if (imageList != null && imageList.size() >0){
            //删除主题详情图附件，重新添加：
            QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
            fileNameWrapper.and(wrapper -> wrapper
                    .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                    .eq("object_id", theme.getId()));
            List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
            if (attachmentList != null && attachmentList.size() >0 ){
                attachmentList.forEach( attachment -> {
                    attachmentService.removeById(attachment.getId());
                });
            }

            List<ThemeAttachmentEntity> listAttachment = new ArrayList<>();
            imageList.forEach(image -> {
                ThemeAttachmentEntity attachment = new ThemeAttachmentEntity();
                attachment.setObjectId(theme.getId());
                attachment.setFileUrl(image);
                attachment.setType(ThemeAttchmentTypeEnum.THEME.getValue());
                attachment.setCreated(new Date());
                listAttachment.add(attachment);
            });
            attachmentService.saveBatch(listAttachment);
        }
        return R.ok();
    }

    /**
     * 上架
     */
    @RequestMapping("/putaway")
    @RequiresPermissions("theme:theme:update")
    public R putaway(@RequestBody ThemeEntity theme){
        ThemeEntity themeEntity = themeService.getById(theme.getId());
        if (themeEntity == null){
            return R.error("该主题不存在,请检查!");
        }
        themeEntity.setStatus(theme.getStatus());
        themeService.updateTheme(themeEntity);
        return R.ok();
    }

    /**
     * 下架
     */
    @RequestMapping("/soldout")
    @RequiresPermissions("theme:theme:update")
    public R soldout(@RequestBody ThemeEntity theme){
        //TODO 查询主题属不属于今日推荐

        //TODO 查询主题属不属于专题
        ThemeEntity themeEntity = themeService.getById(theme.getId());
        if (themeEntity == null){
            return R.error("该主题不存在,请检查!");
        }
        themeEntity.setStatus(theme.getStatus());
        themeService.updateTheme(themeEntity);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("theme:theme:delete")
    public R delete(@RequestBody Long[] ids){
        //TODO 查询主题属不属于今日推荐

        //TODO 查询主题属不属于专题
        
        //删除主题操作：
        List<Long> themeIds = Arrays.asList(ids);
        if (themeIds != null && themeIds.size() > 0){
            themeIds.forEach(themeId ->{
                ThemeEntity themeEntity = themeService.getById(themeId);
                String fileName = themeEntity.getFileName(); //轻奢雅黑.zip
                File file = new File(fileName);
                String fileNameTemp = file.getName().substring(0,file.getName().lastIndexOf("."));
                //删除单个文件
                String themeZip = FileUploadParam.THEME_ZIP.getWebUrl() + fileName;
                OSSFactory.build(null).deleteObject(themeZip);

                //删除整个目录
                String theme = FileUploadParam.THEME.getWebUrl() + fileNameTemp;
                OSSFactory.build(null).deleteObjectDir(theme);

                //删除主题组件和组件配置：
                List<WidgeEntity> widgeList = widgeService.queryWidgeList(themeId);
                widgeList.forEach(widge ->{
                    //themeWidgeLayoutService.deleteThemeWidgeLayoutByThemeWidgeId(themeWidge.getId());
                    widgeLayoutService.remove(Wrappers.<WidgeLayoutEntity>query().lambda().eq(WidgeLayoutEntity::getWidgeId, widge.getId()));
                });
                //themeWidgeService.deleteThemeWidgeByThemeId(themeId);
                widgeService.remove(Wrappers.<WidgeEntity>query().lambda().eq(WidgeEntity::getThemeId, themeId));

                //删除主题详情图附件
                QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
                fileNameWrapper.and(wrapper -> wrapper
                        .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                        .eq("object_id", themeId));
                List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
                if (attachmentList != null && attachmentList.size() >0 ){
                    attachmentList.forEach( attachment -> {
                        attachmentService.removeById(attachment.getId());
                    });
                }

            });
            themeService.deleteTheme(Arrays.asList(ids));
        }
        return R.ok();
    }

    /**
     * 上传图片文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url);
    }

    /**
     * 上传附件文件zip包 zip包名:主题名称-时间(幸福的夏季-20201126.zip)
     * 1、不自定义文件名字，
     * 2、返回url
     * 3、一个主题一个文件夹
     * 4、zip文件的操作：
     *  直接在阿里云解压
     *  下载本地解压重新上传返回url列表关联主题
     *  然后删除本地文件夹个文件
     *
     */
    @PostMapping("/uploadAttachment")
    public R uploadAttachment(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        // 判断主题名称附件是否已经存在
        String fileName = file.getOriginalFilename();
        QueryWrapper<ThemeEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("file_name", fileName));
        List<ThemeEntity> fileNameList = themeService.list(fileNameWrapper);
        if (fileNameList != null && fileNameList.size() >0 ){
            return R.error("该主题附件对应的名称已存在,请更改主题附件名称!");
        }

        //文件前缀 示列:幸福的夏季.zip 幸福的夏季
        String prefix = file.getOriginalFilename().substring(0, file.getOriginalFilename().length()-4) +"";

        //文件后缀 示列:幸福的夏季.zip .zip
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        FileUploadParam themeZip = FileUploadParam.THEME_ZIP;
        themeZip.setSourceDir(aliyunThemeZipDir);
        themeZip.setFileName(prefix);

        UploadParams uploadParam = new UploadParams();
        uploadParam.setFileName(themeZip.getFileName());
        uploadParam.setType(themeZip.getType());
        uploadParam.setSourceDir(themeZip.getSourceDir());
        uploadParam.setWebUrl(themeZip.getWebUrl());

        String url = OSSFactory.build(uploadParam).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url).put("fileName",file.getOriginalFilename());

    }

    public static <T> String parseListToStr(List<T> list){
        String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
        return result;
    }

}
